package com.adui.mgt.performance.service;

import com.adui.mgt.performance.common.CommonConstant;
import com.adui.mgt.performance.common.Result;
import com.adui.mgt.performance.entity.User;
import com.adui.mgt.performance.mapper.UserMapper;
import com.adui.mgt.performance.service.base.impl.BaseServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

import static com.adui.mgt.performance.common.CommonUtil.handleObjLog;

@Service
public class UserService extends BaseServiceImpl<UserMapper, User> {

    public User findUserByName(String username) {
        return this.list(Wrappers.<User>lambdaQuery().eq(User::getUsername, username).eq(User::getDelFlag, CommonConstant.DEL_NO)).stream().findFirst().orElse(null);
    }

    public User findUserById(String id) {
        return this.getById(id);
    }

    public Result findUsers(User user) {

        return Result.data(this.page(new Page<>(user.getPageNum(), user.getPageSize()), Wrappers.<User>lambdaQuery()
                .eq(StringUtils.isNotBlank(user.getUsername()), User::getUsername, user.getUsername())
                .eq(StringUtils.isNotBlank(user.getRealName()), User::getRealName, user.getRealName())
                .eq(StringUtils.isNotBlank(user.getPhone()), User::getPhone, user.getPhone())));
    }

    public Boolean existUsernameFlag(String username) {

        return Objects.nonNull(this.findUserByName(username));
    }

    @Transactional(rollbackFor = Exception.class)
    public Result insertUser(User user) {
        user.setId(null);
        if (this.existUsernameFlag(user.getUsername())) {
            return Result.error("用户名已存在");
        }
        handleObjLog(user);
        this.save(user);
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public Result updateUser(User user) {
        if (StringUtils.isBlank(user.getId())) {
            return Result.error("用户id必传！");
        }
        handleObjLog(user);
        this.updateById(user);
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public Result deleteUser(String id) {
        User user = this.findUserById(id);
        if (Objects.isNull(user)) {
            return Result.error("找不到用户！");
        }
        this.removeById(id);
        return Result.ok();
    }

}
